package com.xiaoxin.experience.util;

import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.io.*;
import java.util.Base64;

/**
 * @author xiaoxin
 */
@Slf4j
public class Base64ChangeUtil {

    private Base64ChangeUtil() {}

    public static String base64Change(String pUrl)
    {
        String result = "";
        try(FileInputStream inputStream = new FileInputStream(pUrl))
        {
            byte[] getData = IOUtil.readInputStream(inputStream);
            result = Base64.getEncoder().encodeToString(getData);
        } catch (IOException e)
        {
            e.printStackTrace();
        }
        return result;
    }

    public static String netFileBase64Change(String pUrl)
    {
        byte[] getData = DownloadUtil.downloadTransToBytes(pUrl);
        if (getData == null)
        {
            return null;
        }
        return Base64.getEncoder().encodeToString(getData);
    }

    public static String readByteToBase64(byte[] data)
    {
        return Base64.getEncoder().encodeToString(data);
    }

    public static String readInputStreamToBase64(InputStream in)
    {
        return readByteToBase64(IOUtil.readInputStream(in));
    }

    public static void saveBase64ToImg(String base64, String extend, String fileName)
    {
        if (base64.contains("data:"))
        {
            int start = base64.indexOf(",");
            base64 = base64.substring(start + 1);
        }
        try
        {
            ImageIO.write(ResizeImgBase64Util.base64String2BufferedImage(base64),extend,new File(fileName));
        }
        catch (IOException e)
        {
            log.error("save img fail: ",e);
        }
    }

    public static void readBase64FileSaveToImg(String base64File,String extend, String fileName)
    {
        byte[] bytes = FileUtil.readAllFileToBytes(base64File);
        String base64 = new String(bytes);
        saveBase64ToImg(base64,extend,fileName);
    }
}
